package com.fer.intercepter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.fer.utils.JWTUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;
import java.nio.channels.AcceptPendingException;
import java.nio.file.AccessDeniedException;
import java.util.Calendar;
import java.util.Date;


//登录拦截器
@Slf4j
public class BossIntercepter implements HandlerInterceptor {
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String method = request.getMethod();
        if (method.equals("OPTIONS")) return true;
        // 1、session实现
//        HttpSession session = request.getSession();
//        String username = (String)session.getAttribute("username");
//        log.info("用户名： {} 请求, sessionId为：{}",username,session.getId());
//        String id = session.getId();
//        log.info("sessionId为：{}", id);
//        if (username == null ||username.equals("") ) {
//            throw new AccessDeniedException("请先登录！");
//        }
        // 2、jwt实现
        String token = null;
        String username = null;
        Cookie[] cookies = request.getCookies();
        if (cookies == null) {
            System.out.println("cookies为null");
            return false;
        }
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals("token")) {
                token = cookie.getValue();
            }else if (cookie.getName().equals("username")) {
                username = cookie.getValue();
            }
        }
        boolean isSuccess = true;
        // 先验证token的合法性，不合法下面的方法会抛出异常
        DecodedJWT verify = null;
        try {
            verify = JWTUtils.verify(token);
        } catch (Exception e) {
            log.error("验证错误！");
            isSuccess = false;
            e.printStackTrace();
        }
        String payload = verify.getPayload();
        String decodedString = new String(Base64.decodeBase64(payload.getBytes()));
        JSONObject jsonObject = JSON.parseObject(decodedString);
        String usernameFromToken = (String)jsonObject.get("username");
        String ipAddressFromToken = (String)jsonObject.get("ipAddress");
        if (username == null || username.equals("") || !username.equals(usernameFromToken)
                || !ipAddressFromToken.equals(request.getRemoteAddr())) {
            System.out.println(username == null || username.equals("") || !username.equals(usernameFromToken));
            System.out.println(!ipAddressFromToken.equals(request.getRemoteAddr()));
            isSuccess = false;
        }
        if (!isSuccess) {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=utf-8");
            PrintWriter out = null;
            JSONObject res = new JSONObject();
            res.put("code", 403);
            res.put("message", "请先登录！");
            out = response.getWriter();
            out.append(res.toString());
            response.setStatus(403);
            log.info("preHandle执行完毕！=== 403");
            return false;
        }
        log.info("preHandle执行完毕！=== 200");

        return true;
    }

}
